/**
 *
 * queue.c - Copy Queue Library
 *
 * The MIT License
 *
 * Copyright (c) 2008 John Van Enk
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#include <stdlib.h>

#include "queue.h"
#include "cpq_error.h"

/**
 * Functions
 */

CPQ_Error_e_t CPQ_Queue_Init(CPQ_Queue_s_t * queue)
{
    queue->first = 0;
    queue->last = 0;
    queue->count = 0;

    return CPQ_ERR_OK;
}

CPQ_Error_e_t CPQ_Queue_Enqueue(CPQ_Queue_s_t * queue, CPQ_Queue_Element_s_t * element)
{
    if(0 == queue->first)
    {
        queue->first = element;
        queue->last = queue->first;
    }
    else
    {
        queue->last->next = element;
        queue->last = queue->last->next;
    }

    (queue->count)++;
    queue->last->next = 0;

    return CPQ_ERR_OK;
}

CPQ_Queue_Element_s_t * CPQ_Queue_Dequeue(CPQ_Queue_s_t * queue)
{
    CPQ_Queue_Element_s_t * e = queue->first;

    queue->first = queue->first->next;

    (queue->count)--;

    return e;
}

CPQ_Queue_Element_s_t * CPQ_Queue_Peek(CPQ_Queue_s_t * queue)
{
    return queue->first;
}

CPQ_Error_e_t CPQ_Queue_Clear(CPQ_Queue_s_t * queue)
{
    CPQ_Queue_Element_s_t * e;

    do
    {
        e = CPQ_Queue_Dequeue(queue);

        if(e->value)
        {
            free(e->value);
        }

        free(e);

        (queue->count)--;
    } while(queue->count > 0);

    return CPQ_ERR_OK;
}
